package controller

import (
	"context"
	"mldong/api/base"
	"mldong/utility"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/gogf/gf/v2/util/gconv"
)

func init() {
	// 注册控制器时自动注入依赖
	utility.RegisterController(&LowcodeController{})
}

type LowcodeSelectReq struct {
	g.Meta `path:"/{module}/{table}/select" tags:"低代码相关接口" method:"post" summary:"通用下拉"`
	base.PageParam
	Module string `in:"path" description:"模块前缀，如sys、dev、wf等" v:"required"`
	Table  string `in:"path" description:"表名小驼峰，如：user、role、dict、dictItem等" v:"required"`
}
type LowcodeController struct {
}

// 通用下拉
func (ctrl *LowcodeController) Select(ctx context.Context, req *LowcodeSelectReq) (res *base.CommonResult, err error) {
	// 传递以m_开头的查询参数
	req.QueryParamMap = utility.GetQueryParamMap(ctx)
	PageNum := 1
	PageSize := 1000
	if req.PageNum != nil {
		req.PageNum = &PageNum
	}
	if req.PageSize != nil {
		req.PageSize = &PageSize
	}
	module := g.RequestFromCtx(ctx).GetRouter("module").String()
	table := g.RequestFromCtx(ctx).GetRouter("table").String()
	tableName := module + "_" + gstr.CaseSnake(table) // 使用gstr转换
	options, err := utility.Select(ctx, tableName, req.PageParam, func(model *gdb.Model) *gdb.Model {
		return model
	})
	if err != nil {
		return
	}
	// 将options中的value转为字符串
	for i, option := range options {
		if option.Value != nil {
			// 使用gconv安全转换
			options[i].Value = gconv.String(option.Value)
		}
	}
	jsonData := base.Data(options)
	g.RequestFromCtx(ctx).Response.WriteJson(jsonData)
	return
}
